<?php
/**
 *
 *
 */
namespace Yz\modules\Generic;


class Controller_Page
    extends Controller_List
{

    const ERROR_WRONG_PAGE = ':WrongPage';

    /** The list of required arguments for controller
     *  @var array
     */
    protected $arguments = array(
        'pageNumber',
    );

    /**
     *
     */
    protected $pager;
    protected $pageNumber;


    /****************************
     *      Public methods      *
     ****************************/

    /** Custom error handler for page:
     *      Handles page-not-found and invalid-number-of-args
     *
     *  @return this|false
     */
    public function doError( \Yz_Exception $ex )
    {
        if ($ex instanceof \Yz_Controller_Exception_InvalidArgument) {
            $t = $this->selectTemplate('Error');
            $t->errorMessage = $this->getErrorMessage() . self::ERROR_WRONG_PAGE;
            return $this->outputTemplate($t);
        }
        return parent::doError($ex);
    }


    protected function setPageNumber($pageNr)
    {
        $this->pageNumber = \Yz_Int::testPositive($pageNr);
        return $this;
    }


    /**
     *
     */
    protected function fetchData()
    {
        $pagerClass = $this->module->resolveClass("Pagination_Default");
        $pager = new $pagerClass($this->pageNumber);
        $this->list = $this->selectModel()->fetchPage($pager);
        $this->pager = $pager;
        return $this;
    }


    /**
     *
     */
    protected function assignTemplateParams(\Yz_Template_Interface $t)
    {
        $t->list = $this->list;
        $t->pager = $this->pager;
        $t->pageNumber = $this->pageNumber;
        return $this;
    }

}
